How do I add image to this canvas ball? - javascript

I am trying to make a simple game, though if I need an image for my bouncing ball then how do I do this?
I am doing this-
function draw() {
ctx.clearRect(0, 0, 300, 300);
if (ctx.getContext) {
Snooker = new Image();
Snooker.onload = loadingComplete;
Snooker.src = "http://www.wpclipart.com/toys/balls/red_snooker_ball.png";
}
x += dx;
y += dy;
bounce();
}
And->
function init() {
var ctx = document.getElementById("canvas");
return setInterval(draw, 10);
}
Now canvas is blank.
Here is fiddle link-
http://jsfiddle.net/stackmanoz/QcLTw/1/
Image I want to add instead of this simple ball-
http://www.wpclipart.com/toys/balls/red_snooker_ball.png

Here is a working version of your script using the image instead of the arc. You would want to load an img using Javascript's new Image() and then set the source to the image you want. Then use drawImage instead of arc.
http://jsfiddle.net/QcLTw/7/

Related

How can I get full image after zooming in canvas

I am facing this issue where once I zoom in on some image in the canvas in javascript, some part of the image goes outside of the canvas. Then I am drawing something on it. But now, I want the latest total image instead of just what is on the canvas frame. How can I get that?
Here is my code for it. Whenever a scroll-up or scroll-down happens, the below function gets called.
var zoom = function(clicks)
{
original = canvas.toDataURL();
// clear the canvas
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
// translate the image according to zoom factor and location of zoom
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
// draw te image on canvas
const img = document.createElement("img");
img.setAttribute("src", original);
img.onload = function () {
ctx.drawImage( img, 0, 0, canvas.width, canvas.height);
};
}

How to draw multi images of the same object onto a single canvas

I want to draw onto a canvas multi times with the same image, in other words i want to apply code that will when i click on the canvas area produces an image and when i click again somewhere else it produces another image and so on.
<canvas></canvas>
But when trying to draw again it instead replaces the previous image that was drawn and then draws the new image. instead of keeping the previous drawn image on the canvas.
function drawAll(){
context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height,0, 0, 700, 618);
if(coordinates.length > 0){
coordinates.map((coord, key) =>{
context.beginPath();
context.moveTo(coord.startX, coord.startY);
context.lineTo(coord.toX,coord.toY);
context.strokeStyle="rgb(226, 104, 36)";
context.lineWidth=2;
context.stroke();
});
}
if(entry){
context.drawImage(imageObjBall, entry.posX-8, entry.posY-8, 16, 16);
}
}
EDIT: Hey sorry forgot to insert this bit down here
function handleClick(e){
if(!isDrawing && prize_id != null){
var pos = getMousePos(canvas, e);
mouseX = pos.x;
mouseY = pos.y;
$x_id=`#cor_x_${prize_id}`;
$y_id=`#cor_y_${prize_id}`;
context.clearRect(0, 0, 700, 618);
context.drawImage(imageObjBall, mouseX-8, mouseY-8, 16, 16);
entry={posX:mouseX,posY:mouseY};
$($x_id).text(mouseX);
$($y_id).text(mouseY);
drawAll();
}
}
NOTE: This is in laravel 5, there is more code outside of this but i
felt this was the necessary snipped needed for you to be able to help
me but if you need more please ask me to edit some more code into this
post
To draw multiple images onto the canvas using a single image object, create the image object via new Image() and set the src property accordingly.
Alternatively, you can also write an <img src=""> tag in the HTML code and get a reference to it via document.querySelector.
There is one important thing to consider: Before you call drawImage, you have to make sure the image is loaded, even when there are no load times (eg. localhost or data-url).
In my example, I solved this by not starting the animation immediately. Instead, the requestAnimationFrame loop is started in the image onload event.
var R = Math.random
var a = document.getElementById("a")
var W = a.width = 400
var H = a.height = 300
var c = a.getContext("2d")
var img = new Image()
img.src = 'https://assets-cdn.github.com/images/icons/emoji/unicode/1f60d.png'
function loop() {
var rndX = (R()*W)|0
var rndY = (R()*H)|0
c.drawImage(img, rndX, rndY)
requestAnimationFrame(loop)
}
img.onload=function() {
loop()
}
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
<canvas id="a"></canvas>

html5 canvas context .fillStyle not working

Just giving canvas a go for the first time with the intention of creating a game. I have an image displaying but oddly the fillStyle method doesn't seem to be working. ( At least the canvas background is still white in google chrome.)
Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? i can't see the problem, would appreciate if anyone else could.
LD24.js:
const FPS = 30;
var canvasWidth = 0;
var canvasHeight = 0;
var xPos = 0;
var yPos = 0;
var smiley = new Image();
smiley.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
var canvas = null;
window.onload = init; //set init function to be called onload
function init(){
canvasWidth = document.getElementById('canvas').width;
canvasHeight = document.getElementById('canvas').height;
canvas = document.getElementById('canvas').getContext('2d');
setInterval(function(){
update();
draw();
}, 1000/FPS);
}
function update(){
}
function draw()
{
canvas.clearRect(0,0,canvasWidth,canvasHeight);
canvas.fillStyle = "#FFAA33"; //orange fill
canvas.drawImage(smiley, xPos, yPos);
}
LD24.html:
<html>
<head>
<script language="javascript" type="text/javascript" src="LD24.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
<p> Your browser does not support the canvas element needed to play this game :(</p>
</canvas>
</body>
</html>
3 notes:
fillStyle does not cause your canvas to be filled. It means that when you fill a shape it will be filled with that color. Therefore you need to write canvas.fillRect( xPos, yPos, width, height).
Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.
Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.
Wait till image loads as well:
var img = new Image();
img.onload = function() {
handleLoadedTexture(img);
};
img.src = "image.png";
function handleLoadedTexture(img) {
//call loop etc that uses image
};
Or maybe you were just missing
canvas.fill();
after
canvas.drawImage(smiley, xPos, yPos);

Image is flickering continuously in pressing button?

The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.

HTML canvas - drawing disappear on resizing

I have created a basic shape in HTML canvas element which works fine.
The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this the normal behavior? or is there a function that can be used to stop this?
One way to fix this could be to call drawing function again on canvas resize however this may not be very efficient if there is huge content to be drawn.
What's the best way?
Here is the link to sample code https://gist.github.com/2983915
You need to redraw the scene when you resize.
setting the width or height of a canvas, even if you are setting it to the same value as before, not only clears the canvas but resets the entire canvas context. Any set properties (fillStyle, lineWidth, the clipping region, etc) will also be reset.
If you do not have the ability to redraw the scene from whatever data structures you might have representing the canvas, you can always save the entire canvas itself by drawing it to an in-memory canvas, setting the original width, and drawing the in-memory canvas back to the original canvas.
Here's a really quick example of saving the canvas bitmap and putting it back after a resize:
http://jsfiddle.net/simonsarris/weMbr/
Everytime you resize the canvas it will reset itself to transparant black, as defined in the spec.
You will either have to:
redraw when you resize the canvas, or,
don't resize the canvas
One another way is to use the debounce if you are concerned with the performance.
It doesnt resize or redraw every position you are dragging. But it will resize only when the it is resized.
// Assume canvas is in scope
addEventListener.("resize", debouncedResize );
// debounce timeout handle
var debounceTimeoutHandle;
// The debounce time in ms (1/1000th second)
const DEBOUNCE_TIME = 100;
// Resize function
function debouncedResize () {
clearTimeout(debounceTimeoutHandle); // Clears any pending debounce events
// Schedule a canvas resize
debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);
}
// canvas resize function
function resizeCanvas () { ... resize and redraw ... }
I had the same problem. Try following code
var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
It keeps the drawing as it is
One thing that worked for me was to use requestAnimationFrame().
let height = window.innerHeight;
let width = window.innerWidth;
function handleWindowResize() {
height = window.innerHeight;
width = window.innerWidth;
}
function render() {
// Draw your fun shapes here
// ...
// Keep this on the bottom
requestAnimationFrame(render);
}
// Canvas being defined at the top of the file.
function init() {
ctx = canvas.getContext("2d");
render();
}
I had the same problem when I had to resize the canvas to adjust it to the screen.
But I solved it with this code:
var c = document.getElementById('canvas');
ctx = c.getContext('2d');
ctx.fillRect(0,0,20,20);
// Save canvas settings
ctx.save();
// Save canvas context
var dataURL = c.toDataURL('image/jpeg');
// Resize canvas
c.width = 50;
c.height = 50;
// Restore canvas context
var img = document.createElement('img');
img.src = dataURL;
img.onload=function(){
ctx.drawImage(img,20,20);
}
// Restote canvas settings
ctx.restore();
<canvas id=canvas width=40 height=40></canvas>
I also met this problem.but after a experiment, I found that Resizing the canvas element will automatically clear all drawings off the canvas!
just try the code below
<canvas id = 'canvas'></canvas>
<script>
var canvas1 = document.getElementById('canvas')
console.log('canvas size',canvas1.width, canvas1.height)
var ctx = canvas1.getContext('2d')
ctx.font = 'Bold 48px Arial'
var f = ctx.font
canvas1.width = 480
var f1 = ctx.font
alert(f === f1) //false
</script>

Categories

Resources