Shapes not appearing on html canvas

I am trying to make a game on an html canvas, however nothing is appearing on the canvas. I am not sure what I am doing wrong. This is the code where I attempt to draw the shapes and start the game:

function startGame() {     myGamePiece = new component(50, 10, "grey", 240, 20);     myAponent = new component(50, 10, "grey", 240, 460);     myScore = new component("30px", "Consolas", "black", 280, 40, "text");     myGameArea.start(); } 

If you wish to see all of my code, it is available here:

How to rotate player to face mouse on canvas?

I’m building a basic game using plain javascript and I am trying to rotate my object to follow my mouse.

I’ve tried getting the client’s mouse X and Y then subtracting the canvas width and height divided by two. Then taking those values and inputing it into Math.atan2(). However, I feel the issue may be in my transform and rotate. The code bellow is what I’ve tried.

WIDTH = c.height; HEIGHT = c.width; document.onmousemove = function(ve){             let cX = -c.width / 2;             let cY = -c.height / 2;             let x = ve.offsetX;             let y = ve.offsetY;             var rX = cX + x - 8;             var rY = cY + y - 8;             player.angle = Math.atan2(rX, rY) / Math.PI * 180;         } function update(){                         var now =;                         dt = now - lastUpdate;                         ctx.clearRect(0, 0, WIDTH, HEIGHT);                         ctx.setTransform(1, 0, 0, 1, WIDTH / 2, HEIGHT / 2);                         ctx.rotate(player.angle + 10);                         drawCircle(player.x, player.y, 20, 0, 180, "red");                         tx.setTransform(1, 0, 0, 1, 0, 0); } setInterval(update, dt/10000); 

The player spins around my mouse in wide circles with no apparent pattern. Here’s a gif showing what’s happening.

Canvas drawImage() method – how to offset source image in a scaled and offset origin?


Source image dimensions: – width: 2448 – height: 2448

Canvas dimensions: – width: 375 – height: 375

Image position and scale on the canvas – x: 141.8 (x coordinate where to place the image on the canvas) – y: 214.55 (y coordinate where to place the image on the canvas) – width: 178.7 (the width of the image to use (stretch or reduce the image) – height: 134.1 (the height of the image to use (stretch or reduce the image)

I have called drawImage like this: ctx.drawImage(img, x, y, width, height) ctx.drawImage(img, 141.8, 214.55, 178.7, 134.1);

yes! the image is scaled and positioned correctly on the canvas.

but oh no! it is cutting off the face of my subject! I need to offset the source image while maintaining the positioning and scaling I had on the canvas.

I know that I need to use context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); – sx: x coordinate where to start clipping – sy: y coordinate where to start clipping – swidth: The width of the clipped image – sheight: The height of the clipped image

I need to offset in the x direction by 158 of the original source image (2448 of width)

After hours and hours of trying different equations and reading the documentation to find the correct numbers to fill in the missing variables, I couldn’t figure it out how to offset the source image without altering the positioning and scaling I already had.

I referred to documentation here:

and tried to experiment here


ctx.drawImage(img, x, y, width, height) ctx.drawImage(img, 141.8, 214.55, 178.7, 134.1);  


ctx.drawImage(img, sx, sy, swidth, sheight, 141.8, 214.55, 178.7, 134.1); 

to offset source image by 158 in relation to width of source image (2448)

need the equations and explanation to calculate sx, sy, swidth, and sheight!

Не рисуется квадрат в path на java в canvas

При попытки нарисовать с помощью путей (path) на Canvas квадрат, или несколько квадратов, они не рисуются. Однако если нарисовать круг с помощью путей, то он рисуется свободно. Как мне нарисовать квадрат именно с помощью путей?

Path path = new Path();     Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);      path.addRect(100, 200, 100, 50, Path.Direction.CW);      paint.setStyle(Paint.Style.STROKE);     paint.setStrokeWidth(5);     paint.setColor(Color.GREEN);      canvas.drawPath(path, paint); 

KDE and gnome canvas

Is gnome canvas supported by KDE ? Etherape Crashes when opened within KDE and complains that gnome canvas isnt supported. If this is true is there a way of importing “gnome canvas”. Or are there any other known workarounds ?

Where do I save a Canvas “center position” coordinate in an MVVM architecture?

Assume I have a canvas that has rendered shapes. I can drag-move around that canvas as if I was in a zoomed in image to move all shapes around. Between the Model and ViewModel I have a ServiceLayer (or Controller, however you’d like to call that ) that generates shapes based on generic object-logic and applies the necessary styles, which it then feeds to the ViewModel. Although not completely traditional MVVM, it’s the solution I came up with thinking about how to change the CanvasBehaviour at runtime without switching ViewModels. Now if I want to switch the underlying generic service (perhaps because another tool was selected) I need to save what the current center position is.

It seems like a nitpicky question, but I feel like since I cannot answer this fully and with determination, I might have misunderstood something about the architecture. Here’s what I’m thinking:

  1. It should not be saved in the Model. The model is for all the underlying shapes etc. and has nothing to do with how they’re displayed.
  2. It should not be in the ServiceObject, since it can change dynamically at runtime based on tools and it “feels” wrong to read out the previous center and feed it to a new ServiceObject before replacing it.
  3. It might belong in the ViewModel. the ViewModel prepares the data it receives into the necessary binded collections. I can keep a reference of the center here, and modify the incoming shapes etc. to translate them around this center point. However that means that the “move” tool now needs a reference towards this ViewModel, to tell it how it changed or similarily, but the tools are supposed to be contained in the ServiceObject entirely.
  4. It does definitely not belong in the view, I think.

No logro que cargue mi imagen en el canvas

Estaba creando un blog de prueba mientras aprendía programación web. ¿Por qué no carga? Es sobre café y esas cosas. El canvas es de 1366×120 pero la imagen es de 2000×2000. No sé si tenga que editar la imagen.

var canvas = document.getElementById('banner'); var ctx=canvas.getContext('2d');  var bannerHeader={   url:"bannerCafe.jpg",   cargaOK:false } bannerHeader.imagen=new Image(); bannerHeader.imagen.src=bannerHeader.url; bannerHeader.imagen.addEventListener("load", cargarBanner());  function cargarBanner()   {     bannerHeader.cargaOK=true;     dibujar()   } function dibujar() {   if(bannerHeader.cargaOK=true)   {ctx.drawImage(bannerHeader.imagen,0,0)} }
<canvas id="banner" width="1366" height="130"></canvas> <script src="imagenes.js"></script>

need to make a lightin strike from one oint to another dealing with svg and canvas coordinate [on hold]

I have a svg file that have three areas one is a outer area with points around the edge another is a inner area with point mid away in to the center and at the center are points randomly laid out. Either a animation of lightn, glowing beam, or some other type of animation will be use to visually connect these points together, if i can somehow find away to use a single image as a lightn strike or a glowing beam strike to increase performance… I can get the location of each point from the svg file embedded in the html by dom element method getBoundingClientRect and getClientRects. It seem to work sometime and others time it don’t. Can someone show me or codepen me a example of a svg images made up of two circle one a outer and the other a inner and in the inner varies of points to target and hit. It can be a canvas with just drawing lines from the outer to the inner and from the inner to the varies of points in the inner closer to the center.

Thank you for reading.

Draw in a canvas explanation

I want to draw in a canvas, i saw an example but i don’t understand this : x:event.clientX - rect.left, in this part of the code :

getMousePos : function(event) {         rect = this.canvas.getBoundingClientRect();         return{             x:event.clientX - rect.left,             y:event.clientY -         };     }, 

What does mean the - ? Sorry it’s a beginner question 😀

Create a grid which only exists within the shape – Canvas

I am having trouble doing something in Canvas – I want to create a grid that only exists within that shape. I am able to create the gird to fit the shape if it is a square but if the shape is an unusual shape I do not know how to create the grid.

Here is what I have so far:

const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(75, 50); ctx.lineTo(40, 205); ctx.lineTo(300, 25); ctx.fillStyle = 'green'; ctx.fill();   function drawGrid(context) {   context.globalCompositeOperation = 'destination-out   ';    for (var x = 40.5; x < 300; x += 10) {     context.moveTo(x, 0);     context.lineTo(x, 300);   }    for (var y = 0.5; y < 301; y += 10) {     context.moveTo(0, y);     context.lineTo(300, y);   }    context.strokeStyle = "#ddd";   context.stroke(); }  drawGrid(ctx)