带有内置图像对象的Canvas组件构造函数;t显示's图像
Canvas component constructor with the built-in image object doesn't show's the image
我正在使用画布,并尝试创建一个构造函数"Component"来创建各种元素。这个想法是,它必须能够不仅用一些颜色填充创建的元素,而且用背景图像填充。它可以用颜色填充元素,但无法加载图像。控制台中没有错误。屏幕上什么都没有。需要帮助。现在整个代码是这样的:
var myRect;
function startGame (){
workingArea.create();
myRect = new Component(30, 30, "grass.jpg", 10, 120, 'image');
}
var workingArea = {
canvas: document.createElement('canvas'),
create: function (){
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext('2d');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
};
function Component(width, height, color, x, y, type){
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.type = type;
if (this.type === 'image'){
this.image = new Image();
this.image.src = color;
}
var ctx = workingArea.context;
if (type === 'image'){
this.image.onload = ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
}
else{
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
else{
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
查看如何加载图像,然后在画布上绘制:https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Example_A_simple_line_graph
如果感兴趣的话,这里有一个很好的解释来解释如何在回调中访问"this":如何在回调内访问正确的"this"上下文?
在你的情况下,它应该看起来像:
function Component(width, height, color, x, y, type){
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.type = type;
var ctx = workingArea.context;
if (type === 'image') {
this.image = new Image();
// This is async, so you need to pass your drawImage inside a callback function
this.image.onload = function() {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
}.bind(this); // Bind the "this" to the callback
this.image.src = color; // This is valid, just unfortunate to name it color.
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
相关文章:
- 非常大的图像显示渐进
- CSS Html使图像显示在单选按钮的选项上(单选按钮被CSS隐藏)
- JS照片库.使大图像显示和缩略图可单击
- 多个图像显示带有动态创建的画布的最后一个图像并分配给图像
- 当我在jquery/javascript中单击按钮时加载图像显示
- React图像显示
- 随机图像显示,无重复,使用Javascript
- 将跨度内容(图像url)转换为图像(显示)
- 随机图像显示不止一次
- 节点.js 使用 Multer 上传图像显示未定义
- 范围滑块,用于更改轨道上方对齐圆的直径并使对齐的图像显示在下方
- 使用图像显示和隐藏
- 使用 JavaScript 将文件夹中的图库图像显示到网页中
- 画布到图像显示为无图像(空白)
- 传单不会将本地图像显示为叠加
- 切换此元素时,如何使不同的图像显示,而不是文本
- 在页面加载时将图像显示为弹出窗口
- 如何在模糊浏览器主窗口时将图像显示为叠加层
- iOS在画布上绘制图像显示:无会导致内存泄漏
- JavaScript 图像显示不起作用