javascript - 使用 Javascript Canvas 将图像添加到对象
问题描述
试图用 png 图像替换黑色方块。不确定正确的技术。
我想使用的图像 -
下面是示例所在的代码笔。
https://codepen.io/roys/pen/pJGJON
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var h = window.innerHeight;
var w = window.innerWidth;
canvas.height = h;
canvas.width = w;
function drawRectangle(rect) {
context.beginPath();
context.rect(rect.x, rect.y, rect.width, rect.height);
context.fillStyle = rect.color;
context.fill();
}
//moving rectangle
var mover = {
x: 0,
y: 0,
width: 40,
height: 40,
color: '#000',
down: true,
right: true
}
function animate() {
clear();
render();
rID = requestAnimationFrame(animate);
}
function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function render() {
//set direction
if (mover.down && mover.y >= h-mover.height)
mover.down = false;
if (!mover.down && mover.y <= 0)
mover.down = true;
if (mover.right && mover.x >= w-mover.width)
mover.right = false;
if (!mover.right && mover.x <= 0)
mover.right = true;
//make move
if (mover.right)
mover.x += 10;
else
mover.x -= 10;
if (mover.down)
mover.y += 10;
else
mover.y -= 10;
drawRectangle(mover);
}
animate();
body,
#canvas
{
margin: 0;
padding: 0;
}
#canvas {
display: block;
background-color: lightblue;
}
<canvas id="canvas"></canvas>
解决方案
推荐阅读
- shopify - Shopify :错误:[API] 此操作需要商家批准 write_themes 范围
- android - 使用android将数据插入firebase中的两个表
- api - 蒸汽构建失败
- java - 按下搜索键时弹出 JTable
- javascript - 从文本框中获取输入并将其添加到 jquery get 方法中的 url 端点
- django - Django swagger 特殊字符转义文档
- javascript - href没有链接到外部网址
- python - 从字符串中获取单词的频率
- azure - 无法访问 Azure AD 域服务
- python - 如何用数据集迭代器替换已保存图形的输入,例如占位符?