My goal is simple: Draw icons on top of a background image (specifically a map).
I'm creating a canvas and then using JavaScript to draw the icons on top of it. Unfortunately when I load the icon it increases the scale substantially. Here's my code:
function draw(){
var canvas = document.getElementById("WorldView");
if(!canvas.getContext){return;}
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function(){ctx.drawImage(img,10,10);};
img.src = 'images/ship-icon small.png';
}
HTML:
<body width=100% style="text-align: center;" onload="draw()">
<canvas id="WorldView" ></canvas>
</body>
Why is it increasing the scale automatically and how do I prevent it from doing that? Also, on 'ctx.drawImage(img,10,10);' the '10,10' pushes it further than 10px, more like 50px.
You haven't set any size for the canvas element so the it using the default size of 300 x 150 and if you are using CSS to set a size of the canvas scaling of its content will be the result.
Try doing:
var canvas = document.getElementById("WorldView");
canvas.width = window.innerWidth; /// integer values
canvas.height = window.innerHeight;
(or some other values if filling the window is not the intention).
and then remove the size setting from CSS.
For those of you who need a responsive canvas element. (doing a webcam screenshot feature). My solution was to print first the content in a temporary canvas like this :
originImageCanvas = document.createElement('canvas')
originImageCanvas.width = $(_video).outerWidth()
originImageCanvas.height = $(_video).outerHeight()
originImageCtx = originImageCanvas.getContext('2d')
originImageCtx.drawImage _video, 0, 0, originImageCanvas.width, originImageCanvas.height
hiddenCanvas = document.createElement('canvas')
hiddenCanvas.width = $(_video).outerWidth()
hiddenCanvas.height = $(_video).outerHeight()
ctx = hiddenCanvas.getContext('2d')
unless sourceX?
sourceX = (hiddenCanvas.width / 2) - (sourceWidth / 2)
unless sourceY?
sourceY = (hiddenCanvas.height / 2) - (sourceHeight / 2)
ctx.drawImage originImageCanvas, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, sourceWidth, sourceHeight
Hope it can help anyone !
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.