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. (My javascript draws a number of stars)
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.
Heres my code (I use AJAX search but i've stripped out most of it for readability, sorry if theres any syntax errors):
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
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]);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.