javascript 在画布上绘制一个填充随机颜色方块的圆圈

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22237497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:44:36  来源:igfitidea点击:

Draw a circle filled with random color sqares on canvas

javascripthtmlloopscanvashtml5-canvas

提问by user1854236

I've got pretty strange example to work on... I need to fill a circle with 1x1 pixels, all with different colors in a browser.

我有一个非常奇怪的例子要处理......我需要用 1x1 像素填充一个圆圈,所有这些像素在浏览器中都有不同的颜色。

What I tried, is something like this

我试过的是这样的

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

function createRandomSqaure(destination) {
    var size = destination.height() * destination.width();

    for (var i = 0; i < size; i += 1) {
        destination.append('<div class="pixel" style="background: ' + getRandomColor() + '"></div>');
    }
}

createRandomSqaure($('.pic'));

The case is, it super slow (as you can imagine, loop goes 40k times for 200x200 image), I thought maybe a better way will be drawing It on canvas? And I need to draw a circle filled with this pixels in the end...

情况是,它超级慢(你可以想象,对于 200x200 的图像,循环进行了 40k 次),我想也许更好的方法是在画布上绘制它?最后我需要画一个用这个像素填充的圆圈......

I don't know how to do something like this in a more optimal way, I can use a nodejs server also, but I think generating something like this server side on heroku is a way too much.

我不知道如何以更优化的方式做这样的事情,我也可以使用 nodejs 服务器,但我认为在 heroku 上生成这样的服务器端有点太多了。

I'm just curious what do you guys think, and what is the best way to do something like this?

我只是好奇你们有什么想法,做这样的事情的最佳方法是什么?

回答by

You can use a simple approach like this:

您可以使用这样的简单方法:

  • Draw all the pixels with random colors in a 200x200 grid on a canvas
  • Change composite mode
  • Draw circle on top
  • 在画布上的 200x200 网格中用随机颜色绘制所有像素
  • 更改合成模式
  • 在上面画圆圈

Live demo

现场演示

Results in:

结果是:

enter image description here

在此处输入图片说明

Example:

例子:

var canvas = document.getElementById('canvas'), // get canvas element
    ctx = canvas.getContext('2d'),              // get context
    x, y = 0,                                   // initialize
    dia = canvas.width,
    radius = dia * 0.5;

ctx.translate(0.5, 0.5);                        // to make pixels sharper

for(; y < dia; y++) {                           // walk x/y grid
    for(x = 0; x < dia; x++) {
        ctx.fillStyle = getRndColor();          // set random color
        ctx.fillRect(x, y, 1, 1);               // draw a pixel
    }
}

// create circle

// removes pixels outside next shape
ctx.globalCompositeOperation = 'destination-in'; 
ctx.arc(radius, radius, radius, 0, 2*Math.PI);
ctx.fill();

// reset
ctx.globalCompositeOperation = 'source-over'; 

function getRndColor() {
    var r = 255*Math.random()|0,
        g = 255*Math.random()|0,
        b = 255*Math.random()|0;
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

回答by Brent Echols

I would def use canvas for this, because you are adding tons of overhead by using actual DOM elements.

我会为此使用画布,因为您通过使用实际的 DOM 元素增加了大量开销。

function drawRect(x,y) {
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.rect(x,y,1,1);
    ctx.strokeStyle = getRandomColor();
    ctx.stroke();
}

Its still going to be sucky, but its sucky no matter what unless you have a server generate images or something before hand so the client doesn't get tied up.

它仍然会很糟糕,但无论如何它都很糟糕,除非你有一个服务器预先生成图像或其他东西,这样客户端就不会被束缚。

回答by Oscar Paz

Well, certainly, adding 40000 divs is very slow, and should always be avoided. Tricks like this one were used in the old ways to get dynamic round corners on divs, and it made the page incredibly slower.

嗯,当然,添加 40000 个 div 非常慢,应该始终避免。像这样的技巧被用于在 div 上获得动态圆角的旧方法,它使页面变得非常慢。

So yes, you should use canvas. By the way, you could optimise the way you get a random color:

所以是的,你应该使用画布。顺便说一句,您可以优化获得随机颜色的方式:

var r = Math.floor(Math.Random()* 256);
var g = Math.floor(Math.Random()* 256);
var b = Math.floor(Math.Random()* 256);

var cssColor = 'rgb(' + r +', ' + g + ',' + b +')';