我有一个 HTML5 Canvas ( JSFiddle ),看起来像:
我正在通过以下方法创建球:
function createball(x,y,r,color){
context.beginPath();
context.arc(x,y,r,0,Math.PI*2,true);
context.fillStyle = color;
context.fill();
}
如何用图像填充球?我的意思是图像可能有图案或一些自然色?
最佳答案
您可以创建一个图案并将球的 fillStyle 设置为该图案
这是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/checkerboard.jpg";
function start(){
var pattern=ctx.createPattern(img,'repeat');
ctx.beginPath();
ctx.arc(50,50,15,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=pattern;
ctx.fill();
ctx.stroke();
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>Source Image:</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/checkerboard.jpg'>
<h4>Fill Circle with pattern made from source image</h4>
<canvas id="canvas" width=100 height=100></canvas>
关于javascript - 用图片填充 HTML5 arc - HTML5 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190226/