mon premier petit programme

Pour toutes les discussions javascript, jQuery et autres frameworks
Répondre
valentin
Messages : 31
Enregistré le : 09 avr. 2024, 16:08

mon premier petit programme

Message par valentin » 06 mai 2024, 12:54

bonjour
et encore merci de toutes les aides que j'ai eu
j'ai ramassé ici et la quelque fragment de code
donc je vous met mon petit programme de photo Halftone
je n'ai pas trop de mérite car beaucoup de code vient de site comme
le votre
je joint le programme pour savoir comment créer une fonction sur JS
pour convertir image en base64 et afficher sur un Canvas
exemple:
1: choisir image
2: convertir
3: afficher
voici mon code mais encore trop inconnue pour moi
HTML

Code : Tout sélectionner

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Halftone</title>
  </head>
  <body>
    <br />
    <br />

    <input type="file" id="input" /><br />
    <img id="output" />

    <input type="button" id="saveimage" value="save image" onclick="save()"/>



    <canvas id="canvas1" style="display: none"></canvas>
    <canvas id="myCanvas2"></canvas>;

    <input
      id="lancer"
      type="button"
      value="Cliquer ici pour lancer"
      onclick="halfton(canvas.width,canvas.height)"
      disabled
    />;

    <label2 id="label2" for="tentacles">Nombre de pixels (2-10):</label2>

    <input
      type="number"
      id="tentacles"
      name="tentacles"
      min="2"
      max="10"
      value="4"
    />
    <!-- <input id="myinput" type="file" onchange="encode();" /> -->

    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>

    <script>
      // from http://stackoverflow.com/questions/19032406/convert-html5-canvas-into-file-to-be-uploaded
      //
      // source "canvas.toDataURL("image/png"); "
      //https://gist.github.com/oreoshake/ccb3d14d7292f56ca0ef
      //https://gist.github.com/oreoshake  site
      //

      function uploadCanvas(dataURL) {
        var blobBin = atob(dataURL.split(",")[1]);
        var array = [];
        for (var i = 0; i < blobBin.length; i++) {
          array.push(blobBin.charCodeAt(i));
        }
        var file = new Blob([new Uint8Array(array)], { type: "image/png" });
        var formdata = new FormData();
        formdata.append("image", file);
      }
      //  carge en memoire une image avec un canvas style="display: none"
      //  la convertie en base64
      // et remplace  originale
      var input, canvas, context, output;

      input = document.getElementById("input");
      canvas = document.getElementById("canvas1");
      context = canvas.getContext("2d");
      output = document.getElementById("output");

      input.addEventListener("change", function () {
        var reader = new FileReader();

        reader.addEventListener("loadend", function (arg) {
          var src_image = new Image();

          src_image.onload = function () {
            canvas1.height = src_image.height;
            canvas1.width = src_image.width;
            //context.scale(2,2);
            context.drawImage(src_image, 0, 0);
            var imageData = canvas.toDataURL("image/png");
            output.src = imageData;

            uploadCanvas(imageData);
          };

          src_image.src = this.result;
          //console.log(src_image.src);
        });

        reader.readAsDataURL(this.files[0]);

        document.getElementById("lancer").disabled = false;

        // sa marche pas la position du canvas1
        // document.getElementById("canvas1").offsetTop=200;
      });
    </script>
  </body>
</html>


JS

Code : Tout sélectionner

 let lxx = 0;
  let lyy = 0;
  var tempE;

  var canvas2 = document.getElementById("myCanvas2");
  var ctx2 = canvas2.getContext("2d");

  document.getElementById("output").hidden = false;
  // document.getElementById("myCanvas2").hidden=true;

  const WID = lg;
  const HEI = ht;
  canvas2.width = lg;
  canvas2.height = ht;
  tempE = document.getElementById("tentacles").value;
  // console.log(tempE);
  const num = parseInt(tempE);

  //const num = +tempE;

  let PIXELS_PER_DOT = num;
  //drawpixel();
  const sourceImageData = context.getImageData(0, 0, WID, HEI);

  const positionToDataIndex = (x, y, width) => {
    width = width || WID;
    // data is arranged as [R, G, B, A, R, G, B, A, ...]
    return (y * width + x) * 4;
  };

  // re-maps a value from its original range [minA, maxA] to the range [minB, maxB]
  const map = (value, minA, maxA, minB, maxB) => {
    return ((value - minA) / (maxA - minA)) * (maxB - minB) + minB;
  };

  //Set the transparency value to 0.5
  ctx2.globalAlpha = 3;

  ctx2.fillStyle = "rgb(255, 255, 255)";

  ctx2.fillRect(0, 0, lg, ht);

  for (let y = 0; y < HEI; y += PIXELS_PER_DOT) {
    for (let x = 0; x < WID; x += PIXELS_PER_DOT) {
      lxx = x;
      lyy = y;

      const index = positionToDataIndex(x, y);

      // extract the R, G, B from the source image.
      // because it's grayscale, only the red channel needs to be sampled.
      const value = sourceImageData.data[index];
      var circleRadius = map(value, 0, 255, PIXELS_PER_DOT / 1.5, 0);
      //console.log(circleRadius);

      ctx2.beginPath();
      ctx2.fillStyle = "black";

      circleRadius = circleRadius * 1.2;

      //console.log(circleRadius);
      if (circleRadius > 4) {
        circleRadius = 4;
      }

      ctx2.arc(lxx, lyy, circleRadius, 0, Math.PI * 2);
      //ctx2.rect(lxx,lyy,circleRadius,circleRadius);

      ctx2.closePath();
      ctx2.fill();
    }
  }
}
function save() {
  var link = document.createElement('a');
   link.download = "test.bmp";
   link.href = myCanvas2.toDataURL("image/bmp");
   link.click();
  }
CSS

Code : Tout sélectionner

#lancer {
  position: fixed;
  top: 10px;
  left: 450px;
  opacity: 1;
}
#input {
  position: fixed;
  top: 10px;
  left: 10px;
  opacity: 1;
  color: blue;
}

#label2 {
    position: fixed;
    top: 10px;
    left: 620px;
    opacity: 1;
    color: rgb(52, 26, 122);

}

#tentacles{
    position: fixed;
    top: 10px;
    left: 820px;
    opacity: 1;
    color: rgb(252, 8, 8);
    width:50px;
    height:20px;
}
#saveimage{
  position: fixed;
  top: 10px;
  left: 920px;
  opacity: 1;
  color: rgb(43, 8, 99);
  width:150px;
  height:20px;
}


valentin
Messages : 31
Enregistré le : 09 avr. 2024, 16:08

Re: mon premier petit programme

Message par valentin » 06 mai 2024, 14:36

bonjour
sur le code JS Jai oublié copier une ligne
function halfton(lg, ht) {

Code : Tout sélectionner

function halfton(lg, ht) {
  let lxx = 0;
  let lyy = 0;
  var tempE;

  var canvas2 = document.getElementById("myCanvas2");
  var ctx2 = canvas2.getContext("2d");

  document.getElementById("output").hidden = false;
  // document.getElementById("myCanvas2").hidden=true;

  const WID = lg;
  const HEI = ht;
  canvas2.width = lg;
  canvas2.height = ht;
  tempE = document.getElementById("tentacles").value;
  // console.log(tempE);
  const num = parseInt(tempE);

  //const num = +tempE;

  let PIXELS_PER_DOT = num;
  //drawpixel();
  const sourceImageData = context.getImageData(0, 0, WID, HEI);

  const positionToDataIndex = (x, y, width) => {
    width = width || WID;
    // data is arranged as [R, G, B, A, R, G, B, A, ...]
    return (y * width + x) * 4;
  };

  // re-maps a value from its original range [minA, maxA] to the range [minB, maxB]
  const map = (value, minA, maxA, minB, maxB) => {
    return ((value - minA) / (maxA - minA)) * (maxB - minB) + minB;
  };

  //Set the transparency value to 0.5
  ctx2.globalAlpha = 3;

  ctx2.fillStyle = "rgb(255, 255, 255)";

  ctx2.fillRect(0, 0, lg, ht);

  for (let y = 0; y < HEI; y += PIXELS_PER_DOT) {
    for (let x = 0; x < WID; x += PIXELS_PER_DOT) {
      lxx = x;
      lyy = y;

      const index = positionToDataIndex(x, y);

      // extract the R, G, B from the source image.
      // because it's grayscale, only the red channel needs to be sampled.
      const value = sourceImageData.data[index];
      var circleRadius = map(value, 0, 255, PIXELS_PER_DOT / 1.5, 0);
      //console.log(circleRadius);

      ctx2.beginPath();
      ctx2.fillStyle = "black";

      circleRadius = circleRadius * 1.2;

      //console.log(circleRadius);
      if (circleRadius > 4) {
        circleRadius = 4;
      }

      ctx2.arc(lxx, lyy, circleRadius, 0, Math.PI * 2);
      //ctx2.rect(lxx,lyy,circleRadius,circleRadius);

      ctx2.closePath();
      ctx2.fill();
    }
  }
}
function save() {
  var link = document.createElement('a');
   link.download = "test.bmp";
   link.href = myCanvas2.toDataURL("image/bmp");
   link.click();
  }



valentin
Messages : 31
Enregistré le : 09 avr. 2024, 16:08

Re: mon premier petit programme

Message par valentin » 07 mai 2024, 19:25

bonsoir
je viens d'après l'image créer en base64 (image id output)
effacer pour la remplacer par la même mais en nuance de gris
donc j'essais avec context.clearRect(x, y, largeur, hauteur);
mais sa marche pas
voici mon code nuance de gris

Code : Tout sélectionner

function gris(lg, ht) {
var imgPixels = context.getImageData(0, 0, lg, ht);
    for(var y = 0; y < imgPixels.height; y++){
     for(var x = 0; x < imgPixels.width; x++){
          var i = (y * 4) * imgPixels.width + x * 4;
          var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
          imgPixels.data[i] = avg;
          imgPixels.data[i + 1] = avg;
          imgPixels.data[i + 2] = avg;
     }
    context.clearRect(0,0,lg,ht); 
context.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);

}

valentin
Messages : 31
Enregistré le : 09 avr. 2024, 16:08

Re: mon premier petit programme

Message par valentin » 07 mai 2024, 23:29

bonsoir
je ne sais pas si c'est ideal mais j'ai crée un 3 eme canvas sans affichage

Code : Tout sélectionner

<canvas id="myCanvas3" style="display: none"></canvas>
ensuite j'ai copier les pixels dans ce Canvas en nuance de gris

Code : Tout sélectionner

 document.getElementById("output").src = canvas3.toDataURL();

Code : Tout sélectionner

function gris(lg, ht) {
  var canvas3 = document.getElementById("myCanvas3");
  var cont2 = canvas3.getContext("2d");
  canvas3.width = lg;
  canvas3.height = ht;
  var imgPixels = context.getImageData(0, 0, lg, ht);
  for (var y = 0; y < imgPixels.height; y++) {
    for (var x = 0; x < imgPixels.width; x++) {
      var i = y * 4 * imgPixels.width + x * 4;
      var avg =
        (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
      imgPixels.data[i] = avg;
      imgPixels.data[i + 1] = avg;
      imgPixels.data[i + 2] = avg;
    }
  }

  cont2.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);

  document.getElementById("output").src = canvas3.toDataURL();


}




Répondre