I need to update the background image of a canvas based on what the user selects in a select
dropdown. The url of the image can be found in the value
attributes of the option
tags. But what is the best way for this? I think the image would load on every change in the dropdown. Should I keep all images as img
tags on the page first? Here is my current code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
$("#bg").on("change", function(){
var curSrc = $(this).val();
var image = new Image();
image.src = curSrc;
image.onload = function(){
ctx.drawImage( image, 0, 0, 150, 150 );
}//onload()
});//#bg change()
.as-console
{
display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="150" height="150"></canvas>
<select id="bg">
<option value="http://placehold.it/300x300?text=image+1">Image 1</option>
<option value="http://placehold.it/300x300?text=image+2">Image 2</option>
<option value="http://placehold.it/300x300?text=image+3">Image 3</option>
<select>
Update
My problem is that I have a number of text fields also. And on updating any of those fields (on change) I redraw the canvas, which includes loading and drawing the image again. So, if there are 8 textfields, then even after selecting an image, it will reload at least 8 times while the user fills out the text fields. I wanted to know if this will cause a trip to server or the image will be loaded from cache in such cases.
What I wanted to know is:
1. Will loading same image like I have done multiple times, cause multiple trips to server?
2. Is there any better approach that minimises the number of such round trips to server for loading image?