我在同一页面上有10幅画布。在每个画布上,我正在尝试添加一个现有的图像。这可能吗?我尝试了下一个代码,但没有显示任何图像:
var numberOfPages = $('.draw_pages canvas').length;
var i = 0;
var counter = 0;
for(i=0; i<numberOfPages; i++){
counter++;
var canvas = document.getElementById("canvas_"+counter);
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World "+ counter, 110, 250);
//add images to canvas
var base_image = new Image();
base_image.onload = function(){
init();
}
base_image.src = '../images/page_1.png';
function drawImage(){
ctx.drawImage(base_image, 0, 0, 575, 575);
}
function init(){
drawImage();
}
}
我也尝试过这种方式,但只有当我点击浏览器网址上的输入键并且正在绘制文本时,它才有效:
var numberOfPages = $('.draw_pages canvas').length;
var i = 0;
var counter = 0;
for(i=0; i<numberOfPages; i++){
counter++;
console.log(counter);
var canvas = document.getElementById("canvas_"+counter);
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World "+ counter, 110, 250);
//add images to canvas
drawImage();
function drawImage(){
base_image = new Image();
base_image.src = '../jester/images/page_1.png';
//base_image.onload = function(){
ctx.drawImage(base_image, 0, 0, 575, 575);
//}
}
}
有什么想法吗?
答案 0 :(得分:5)
简单!使用jquery .each()并在其中执行您的操作。
$(function() {
$('canvas').each(function() {
var n = $(this).attr('id').split('_')[1];
var context = this.getContext('2d');
var image = new Image();
image.src = 'http://lorempixel.com/image_output/abstract-q-c-640-480-'+n+'.jpg';
image.onload = function(){
context.drawImage(image, 0, 0, 575, 575);
context.font = '30px Arial';
context.fillText('Hello World '+ n, 20, 20);
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas_1"></canvas>
<canvas id="canvas_2"></canvas>
<canvas id="canvas_3"></canvas>
&#13;