答案 0 :(得分:0)
在进行填充之前,您需要使用移动平移画布。在制作你的形状之前,请记住beginPath
。
var pattern = document.getElementById('pattern');
var can = document.getElementById('can');
var ctx = can.getContext('2d');
var w = can.width = 300;
var h = can.height = 200;
pattern.width = pattern.height = 20;
var pctx = pattern.getContext('2d');
pctx.fillStyle = 'white';
pctx.fillRect(0, 0, 20, 20);
pctx.fillStyle = 'red';
pctx.fillRect(0, 0, 10, 10);
pctx.fillRect(10, 10, 10, 10);
pctx.fillRect(2, 12, 6, 6);
pctx.fillRect(12, 2, 6, 6);
var p = ctx.createPattern(pattern, 'repeat');
var x = 50;
var y = 50;
var radius = 50;
var xStep = 1;
var yStep = 2;
var trans = "on";
function ani() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, w, h);
ctx.moveTo(x, y);
// beginPath clears any existing path
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 20);
ctx.fillStyle = p;
if (trans == "on") {
ctx.save();
// translate will offset the fill pattern
ctx.translate(x, y);
ctx.fill();
ctx.restore();
} else {
ctx.fill();
}
x += xStep;
y += yStep;
if (x > (w - radius) || x < radius) xStep *= -1;
if (y > (h - radius) || y < radius) yStep *= -1;
requestAnimationFrame(ani);
}
ani();
var btnOff = document.getElementById('trans_off');
var btnOn = document.getElementById('trans_on');
btnOff.addEventListener('click',function(){
btnOff.className = "selected";
btnOn.className = "";
trans = "off";
});
btnOn.addEventListener('click',function(){
btnOff.className = "";
btnOn.className = "selected";
trans = "on";
});
body {
background-color: #555555;
color: #F0F0F0;
font-family: sans-serif;
}
button {
color: #cccccc;
background-color: #333333;
border: 1px solid #cccccc;
}
button.selected {
color: white;
font-weight: bold;
}
Translate
<button id="trans_off">off</button>
<button id="trans_on" class="selected">on</button>
<hr/>
<canvas id="pattern"></canvas>
<canvas id="can"></canvas>