• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

115
Vistas
.drawimage() is only showing the bottom left corner of an image

I am trying to crop an image with Javascript. I have croppr.js and it is sending the data and I was trying to crop the image so I can save it to a storage server with Base 64. I have read online about .drawimage(). I have tried:

function process(data) {
    console.log("DATA:" + data)
            var canvas = document.getElementById("canvas")
      var context = canvas.getContext('2d');
      var imageObj = new Image();
            var zoom 
          imageObj.onload = function() {

                context.width = data.width
                context.height = data.height

                // draw cropped image
                var sourceX = data.x;
                var sourceY = data.y;
        var sourceWidth = data.width / 2;
        var sourceHeight = data.height / 2; 
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX =  0;
        var destY =  0;
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                var dataurl = canvas.toDataURL('image/jpeg', 1.0)
                console.log(dataurl)
            };
      imageObj.src = document.getElementsByTagName("img")[0].src;
            console.log(imageObj.src)
}

data Contains X Y Height Width As an JSON array.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First I see is the:

context.width = data.width
context.height = data.height

Did you meant to do canvas instead?

Here is an example:

function process(data) {
  var canvas = document.getElementById("canvas")
  var context = canvas.getContext('2d');
  var img = new Image();
  
  img.onload = function() {
    canvas.width = data.width
    canvas.height = data.height

    // draw cropped image
    var w = data.width / 2;
    var h = data.height / 2;

    context.drawImage(img, data.x, data.y, w, h, 0, 0, w, h);
  };
  img.src = data.src;
}

process({x:0, y:0, width:600, height: 600, src: "http://i.stack.imgur.com/UFBxY.png"})
<canvas id="canvas"></canvas>

That is the only issue I could see on your code.
What is not clear is the data you use to call the process function

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda