我有以下代码将图像渲染为画布的背景:
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 69;
var destY = 50;
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "myImage.jpg";
};
如果现在而不是外部文件,我想使用内嵌图像作为背景怎么办?例如,
<img src="data:image/jpeg;base64,4uPk5ebn6Wql94XOr2gntJRE..." />
如何将其作为画布的背景?
编辑:我找到了一个提到这个的教程(https://developer.mozilla.org/en/Canvas_tutorial/Using_images),但是没有提到如何使用它。
答案 0 :(得分:1)
如果你想将图像写入&#39; canvas&#39;那么你应该使用drawImage api(你已经在做了)。
但是如果你想将图片放到标签上,那么你应该转换&#39;图像文件&#39;到&#39; base64&#39; URI。通常它将由服务器端编程(PHP,Python)check here完成。
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<body onload="do_onload()">
<h1>Hello World!</h1>
<p>
<canvas width="640" height="400" id="myCanvas">
Canvas not supported!
</canvas>
</p>
<script>
function do_onload(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 69;
var destY = 50;
var imageObj = new Image();
imageObj.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QNSRXhpZgAATU0AKgAAAAgABVEAAAQAAAABAAAAAFEBAAMAAAABAAEAAFECAAEAAAMAAAAASlEDAAEAAAABAAAAAFEEAAEAAAAB/AAAAAAAAAAAAAAAADMAAGYAAJkAAMwAAP8AKwAAKzMAK2YAK5kAK8wAK/8AVQAAVTMAVWYAVZkAVcwAVf8AgAAAgDMAgGYAgJkAgMwAgP8AqgAAqjMAqmYAqpkAqswAqv8A1QAA1TMA1WYA1ZkA1cwA1f8A/wAA/zMA/2YA/5kA/8wA//8zAAAzADMzAGYzAJkzAMwzAP8zKwAzKzMzK2YzK5kzK8wzK/8zVQAzVTMzVWYzVZkzVcwzVf8zgAAzgDMzgGYzgJkzgMwzgP8zqgAzqjMzqmYzqpkzqswzqv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DKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9DKKKKAP/2Q==";
imageObj.onload = function(){
context.drawImage(imageObj, destX, destY);
};
};
</script>
</body>
</html>
&#13;
这是一个完整的工作示例。