(HTML5 画布)填充样式 img 不会随我的地形路径移动
(HTML5 Canvas) Fillstyle img doesnt move with my terrain path
我正在写一个画布游戏。我有一些随机生成的地形,用lineTo(),closePath()制作,并用img填充为fillStyle。目前为止,一切都好。但是当我使用 js 移动地形时,img 不会随之移动并停留在同一个地方。有什么想法吗?咔嚓。
在进行填充之前,您需要随动作平移画布。还要记得在制作形状之前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>
相关文章:
- jQuery-将列表项的一个元素移动到同一项的另一个元素中+对我的列表中的每个项执行此操作
- 我的响应菜单在移动版中不起作用
- 我的svg矩形移动
- 为什么当我在带有锚点的页面之间移动时,Rails不重新加载我的javascript文件
- I'我试图在我的网页上动态地上下移动元素.我该怎么做
- context.arc(x,y,r,S角度,E角度,逆时针);我可以在画布上做z方向的移动吗
- 为什么我的导航按钮或按钮文本不会移动到中心
- 如何判断我是否在Ionic2的移动平台上
- 我可以'我似乎没有得到我的网站'移动导航开始工作
- 如何让我的移动菜单按钮显示和隐藏导航栏,以及在负空间中单击时隐藏
- 从博客重定向到我的移动网站
- 我如何使用 php 或 JavaScript 使一个人被重定向到我的移动网站(如果他们在移动设备上)
- 我的移动网站右侧有一个令人讨厌的空白
- 我可以安全地限制桌面用户访问我的移动网站吗
- 如何在我的移动应用程序(cordova)上启用跨域资源共享,它连接到API(在Yii中)
- 我可以使用php嵌入在我的移动网站的javascript
- 从我的网站使用应用程序链接方法到我的移动应用程序的深度链接
- 如果在移动设备上查看,我应该如何首先加载我的移动内容
- 如何组合我的“桌面视图”?带有我的移动视图的HTML文件jQuery移动文件
- Javascript方法不会在我的移动应用程序点击按钮时调用