[英]Multiple HTMl5 canvas elements generated by javascript not appearing (Works fine with a single element)
I'm relatively new to Javascript and i'm trying to generate multiple canvas elements on the same page to use as a "rating" display for products. 我是Java语言的新手,我试图在同一页面上生成多个画布元素,以用作产品的“评级”显示。 (My javascript draws a number of stars) (我的JavaScript画了很多星星)
This works fine when a product search results only returns one product (canvas element) however when there are multiple products, the canvas elements don't even appear on the page or the HTML itself. 当产品搜索结果仅返回一个产品(canvas元素)时,这很好用,但是当有多个产品时,canvas元素甚至不会出现在页面或HTML本身上。
Heres my code (I use AJAX search but i've stripped out most of it for readability, sorry if theres any syntax errors): 这是我的代码(我使用AJAX搜索,但出于可读性考虑,我已经删除了大部分代码,对不起,如果有任何语法错误):
Search.js Search.js
function doRatings(avgRating, results){
/* Print search */
var canvas = new Array();
resultsHTML = '';
for(i=0;i<results.length;i++){
resultsHTML = resultsHTML + '<div id="AvgRating' + i + '"></div> <p>Under canvas</p>';
}
document.getElementById("content").innerHTML = '<div class="section group">' + resultsHTML + '</div>';
if(avgRating > 0){
canvas[i] = document.createElement('canvas');
canvas[i].width = 240;
canvas[i].height = 20;
canvas[i].id = i;
drawRating(canvas[i], avgRating);
document.getElementById("AvgRating" + i).appendChild(canvas[i]);
}
}
DrawStars.js DrawStars.js
function drawRating(canvas, avgRating){
var ctx = canvas.getContext('2d');
//Start star loop
for(var s=0; s<avgRating; s++){
ctx.fillStyle = 'yellow';
ctx.stokeStyle = 'black';
//Work out the angles between each vertex
var a = (2 * Math.PI) / 10; //5 inside and outside angles
var radius = 10; //Determins the size of the stars
//Determine the positioning to draw the start based upon the interation of the loop and the size of the star
var starXY = [((s*(radius * 2 + 4)) + radius), radius];
ctx.beginPath();
//Begin drawing loop for star
for(var i = 11; i != 0; i--){
var r = radius*(i % 2 + 1) / 2;
var o = a * i;
ctx.lineTo((r * Math.sin(o)) + starXY[0], (r * Math.cos(o)) + starXY[1]);
}
ctx.closePath();
ctx.stroke();
ctx.fill();
}}
Adding loop to the canvas creation completes process - see fiddle 将循环添加到画布创建中可以完成过程-参见小提琴
function doRatings(avgRating, results){
/* Print search */
var canvas = new Array();
resultsHTML = '';
for(i=0;i<results.length;i++){
resultsHTML = resultsHTML + '<div id="AvgRating' + i + '"></div> <p>Under canvas</p>';
}
document.getElementById("content").innerHTML = '<div class="section group">' + resultsHTML + '</div>';
for(i=0;i<results.length;i++){
if(avgRating > 0){
canvas[i] = document.createElement('canvas');
canvas[i].width = 240;
canvas[i].height = 20;
canvas[i].id = i;
drawRating(canvas[i], avgRating);
document.getElementById("AvgRating" + i).appendChild(canvas[i]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.