gpt4 book ai didi

javascript - 深入了解 HTML5 Canvas fillStyle

转载 作者:行者123 更新时间:2023-11-29 18:07:18 26 4
gpt4 key购买 nike

JSFiddle Link (But, please read first)

假设,我有一个 400 x 200

的 Canvas
<canvas id="myCanvas" width="400" height="200"></canvas>

我在 Canvas 上添加了一个 40 x 40 的球:(参见下面的函数)

createdBall(20,20,20)

在此函数中,球的中心位于左上角 20px 处,半径为 20px。 (与使用的原始图像尺寸相同)

function createBall(x,y,r){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");

context.beginPath();
context.arc(x,y,r,0,Math.PI*2,true);
context.fillStyle = context.createPattern(img, 'repeat');
context.fill();

}

结果是: enter image description here

现在,我再添加一些球:fillStyle 搞砸了。

createBall(50,50,20);
createBall(80,80,20);

enter image description here

我发现整个 Canvas 像这样被填满一秒钟会发生什么,只有我们想要填充的部分被选中。是这样的: enter image description here

这正是我的球发生的事情。如何用图像填充我的每个球?

最佳答案

您可以使用变换/平移代替 arc 的 x-y,参见 here :

createBall(20, 20, 20);
createBall(50, 50, 20);
createBall(80, 80, 20);

function createBall(x,y,r){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");

context.beginPath();
context.translate(x - r, y - r);
context.arc(r, r, r, 0, Math.PI * 2, true);
context.fillStyle = context.createPattern(img, 'repeat');
context.fill();
context.translate(-(x - r), -(y - r));
}

...and this works because... translate(x,y) is actually pushing the canvas's [0,0] origin rightward and downward to [x,y]. This also pushes the image-pattern from left-top to [x,y] so that it now nicely fits inside the arc. BTW, it's more efficient to create the pattern once outside the createBall function. ;-) — @markE

关于javascript - 深入了解 HTML5 Canvas fillStyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30316562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com