我想写在Image之上。所以我试图使用onLoad函数设置canvas对象的背景图像。 drawImage()在画布上工作和绘制,但如果我尝试设置画布背景图像,它就不起作用。
这有效
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
canvas.style.backgroundRepeat = "no-repeat";
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
这不起作用
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
canvas.style.backgroundRepeat = "no-repeat";
imageObj.onload = function() {
canvas.style.backgroundImage = 'url('+imageObj+')';
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
答案 0 :(得分:2)
你不能在一个风格中使用一个对象,它只能是字符串:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'
canvas.style.backgroundRepeat = "no-repeat";
canvas.style.backgroundImage = 'url('+image+')';