javascript - 用图片填充 HTML5 arc - HTML5 Canvas

标签 javascript html canvas html5-canvas

我有一个 HTML5 Canvas ( JSFiddle ),看起来像: enter image description here

我正在通过以下方法创建球:

function createball(x,y,r,color){
    context.beginPath();
    context.arc(x,y,r,0,Math.PI*2,true);
    context.fillStyle = color;
    context.fill();

}

如何用图像填充球?我的意思是图像可能有图案或一些自然色?

最佳答案

您可以创建一个图案并将球的 fillStyle 设置为该图案

enter image description here

这是示例代码和演示:

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/

相关文章:

javascript - 在javascript中的HTTP POST请求中发送cookie

javascript - 如何在javascript中用ID替换名称

javascript - 为什么javascript中数组符号前的加号返回零

javascript - CSS 过渡不起作用

html - 在没有 jquery 的情况下为每第 4 个奇数/偶数 nth-child(2n) 设置样式

javascript - 从 jQuery 中的多个相同类名获取值 CSS

javascript - 使用 css 设置 Canvas 宽度和高度会移动笔

javascript - 滚动动画脚本。它只运行一次

javascript - 使用 Canvas 使对象的尺寸在大小上振荡

javascript - 删除在图像 Canvas HTML5 上绘制的彩色线条