logo
down
shadow

How to copy an area from a canvas into an image


How to copy an area from a canvas into an image

By : Trapezoid
Date : November 15 2020, 06:54 AM
Does that help With some trial and error I managed to get something working that supposedly comes close to what you want.
code :
public class CopyArea {

  public static void main( String[] args ) {
    CopyArea copyArea = new CopyArea();
    copyArea.create();
    copyArea.run();
  }

  private Display display;
  private Image sourceImage;
  private Point canvasSize;
  private Shell shell;
  private Canvas source;
  private Canvas destination;
  private Point snippetOrigin;
  private Image snippet;

  CopyArea() {
    display = new Display();
    sourceImage = new Image( display, getClass().getResourceAsStream( "mona-lisa.jpeg" ) );
    canvasSize = new Point( sourceImage.getBounds().width, sourceImage.getBounds().height );
    shell = new Shell( display );
    source = new Canvas( shell, SWT.NONE );
    destination = new Canvas( shell, SWT.NONE );
  }

  void create() {
    shell.setLayout( new RowLayout() );
    source.setLayoutData( new RowData( canvasSize ) );
    source.addPaintListener( new PaintListener() {
      @Override
      public void paintControl( PaintEvent event ) {
        event.gc.drawImage( sourceImage, 0, 0 );
        if( snippetOrigin != null ) {
          snippet = new Image( display, 40, 40 );
          event.gc.copyArea( snippet, snippetOrigin.x, snippetOrigin.y );
          destination.redraw();
          snippetOrigin = null;
        }
      }
    } );
    source.addMouseListener( new MouseAdapter() {
      @Override
      public void mouseDown( MouseEvent event ) {
        snippetOrigin = new Point( event.x, event.y );
        source.redraw();
      }
    } );
    destination.setLayoutData( new RowData( canvasSize ) );
    destination.addPaintListener( new PaintListener() {
      @Override
      public void paintControl( PaintEvent event ) {
        event.gc.setBackground( display.getSystemColor( SWT.COLOR_WHITE ) );
        event.gc.fillRectangle( event.gc.getClipping() );
        if( snippet != null ) {
          event.gc.drawImage( snippet, 0, 0 );
        }
      }
    } );
  }

  void run() {
    shell.pack();
    shell.open();
    while( !shell.isDisposed() ) {
      if( !display.readAndDispatch() )
        display.sleep();
    }
    display.dispose();
  }
}


Share : facebook icon twitter icon
Fill canvas area with an image instead of color

Fill canvas area with an image instead of color


By : Hamish Fawns
Date : March 29 2020, 07:55 AM
Any of those help Using below code i'm able to draw an area on an image loaded into a canvas and fill the drawn area with some color. , something like this :
code :
$(function() {
  var canvas = $('#canvas')[0];
  var ctx    = canvas.getContext('2d');
  var src    = "http://www.mysite.com/avatar/e55?s=128&d=identicon&r=PG";
  var w      = canvas.width  = 400;
  var h      = canvas.height = 400;
  var img    = new Image();
  img.src    = src;
  $(img).load(function() {
    var pattern = ctx.createPattern(img, 'repeat');
    ctx.fillStyle = pattern;
    ctx.fillRect(0, 0, w, h);
  });
});
How to use Data URI to copy canvas as image or another canvas

How to use Data URI to copy canvas as image or another canvas


By : Nguyen Tung Anh
Date : March 29 2020, 07:55 AM
This might help you I converted an image to canvas and made changes to it and want to convert the canvas with changes to a Data URI and use that for the source of image object or another canvas , You've almost got it.
code :
  var imageObj = new Image();
  imageObj.onload = function(){

      ...

      var image = new Image();
      image.onload=function(){

          ...

      }
      image.src=canvas.toDataURL(); // .png is the default


  };
  imageObj.crossOrigin="anonymous";
  imageObj.src=imageURI;
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px; }
    canvas{border:1px solid red;}
    img{border:1px solid blue;}
</style>

<script>
$(function(){

    var lat="lat";
    var lon="long";

    onPhotoURISuccess("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png");

    function onPhotoURISuccess(imageURI) {

            var largeImage = document.getElementById('testImage'); //image object

            var canvas = document.getElementById('canvasPnl');// source canvas
            var context= canvas.getContext("2d");
            var imageObj = new Image();
            imageObj.onload = function(){
                context.drawImage(imageObj,0,0,100,100 );
                context.fillStyle="#FFFFFF";
                context.fillText('Latitude:'+ lat.toString()+'Longitude:'+ lon.toString(),0,10);
                context.fillText(new Date(), 0, 20);


    //            context.save(); // where's the matching context.restore();


                var image = new Image();
                image.onload=function(){
                    var canvas2 = document.getElementById('canvasPnl2');//destination canvas
                    var context2= canvas2.getContext("2d");
                    context2.drawImage(image,0,0);
                    largeImage.src=canvas2.toDataURL();
                }
                image.src=canvas.toDataURL(); // .png is the default


            };
            imageObj.crossOrigin="anonymous";
            imageObj.src=imageURI;


    }        

}); // end $(function(){});
</script>

</head>

<body>
    <p>Pnl</p>
    <canvas id="canvasPnl" width=100 height=100></canvas>
    <p>Pnl2</p>
    <canvas id="canvasPnl2" width=100 height=100></canvas>
    <p>testImage</p>
    <img id=testImage src="houseicon.png" width=100 height=100 >
</body>
</html>
Highlight area of image with canvas/JS

Highlight area of image with canvas/JS


By : Asrsagar
Date : March 29 2020, 07:55 AM
like below fixes the issue What @Ken said but I think some of his code example was accidentally omitted:
code :
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var cw=700;
    var ch=438;

    var img=new Image();
    img.onload=start;
    img.src="cat.jpg";
    function start(){
        canvas.width=cw;
        canvas.height=ch;

        // draw the image on the canvas
        ctx.drawImage(img,0,0,cw,ch);

        // darken the image with a 50% black fill
        ctx.save();
        ctx.globalAlpha=.50;
        ctx.fillStyle="black";
        ctx.fillRect(0,0,cw,ch);
        ctx.restore();

        // ctx.clip() the area to highlight
        // and redraw the whole image
        // (the image will draw only in the clipping region)
        ctx.save();
        ctx.beginPath();
        ctx.clearRect(300,100,200,100);
        ctx.rect(300,100,200,100);
        ctx.clip();
        ctx.drawImage(img,0,0,cw,ch);
        ctx.restore();

    }

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Duplicating a canvas many times: clone the canvas or copy the image data?

Duplicating a canvas many times: clone the canvas or copy the image data?


By : user3607941
Date : March 29 2020, 07:55 AM
wish of those help Cloning a canvas will duplicate its dimensions and styling, but not its image data. You can copy the image data by calling drawImage on the context. To paint the contents of originalCanvas onto duplicateCanvas, write:
code :
duplicateCanvas.getContext('2d').drawImage(originalCanvas, 0, 0);
function message(s) {
  document.getElementById('message').innerHTML += s + '<br />';
}

function timeIt(action, description, initializer) {
  var totalTime = 0,
      initializer = initializer || function () {};
  initializer();
  var startTime = performance.now();
  action();
  var elapsed = performance.now() - startTime;
  message('<span class="time"><span class="number">' +
      Math.round(elapsed * 1000) + ' &mu;s</span></span> ' + description);
}

function makeCanvas() {
  var canvas = document.createElement('canvas'),
      context = canvas.getContext('2d');
  canvas.width = 100;
  canvas.height = 100;
  timeIt(function () {
    context.fillStyle = '#a63d3d';
    context.fillRect(10, 10, 80, 40);   // Paint a small scene.
    context.fillStyle = '#3b618c';
    context.beginPath();
    context.arc(60, 60, 25, 0, 2*Math.PI);
    context.closePath();
    context.fill();
  }, '(millionths of a second) to draw original scene', function () {
    context.clearRect(0, 0, canvas.width, canvas.height);
  });
  return canvas;
}

// copyCanvas returns a canvas containing the same image as the given canvas.
function copyCanvas(original) {
  var copy;
  timeIt(function () {
    copy = original.cloneNode();  // Copy the canvas dimensions.
    copy.getContext('2d').drawImage(original, 0, 0);  // Copy the image.
  }, 'to copy canvas with cloneNode and drawImage');
  return copy;
}

// imageFromStorage extracts the image data from a canvas, stores the image data
// in a browser session, then retrieves the image data from the session and
// makes a new image element out of it. We measure the total time to retrieve
// the data and make the image.
function imageFromStorage(original) {
  var image,
      dataURI = original.toDataURL();
  timeIt(function () {
    image = document.createElement('img');
    image.src = dataURI;
  }, 'to make image from a dataURI');
  return image;
}

function pageLoad() {
  var target = document.getElementById('canvases'),
      containers = {},  // We'll put the canvases inside divs.
      names = ['original', 'cloneNode', 'drawImage', 'dataURI'];
  for (var i = 0; i < names.length; ++i) {
    var name = names[i],  // Use the name as an ID and a visible header.
        container = document.createElement('div'),
        header = document.createElement('div');
    container.className = 'container';
    header.className = 'header';
    header.innerHTML = container.id = name;
    container.appendChild(header);
    target.appendChild(container);
    containers[name] = container;  // The canvas container is ready.
  }
  var canvas = makeCanvas();
  containers.original.appendChild(canvas);  // Original canvas.
  containers.cloneNode.appendChild(canvas.cloneNode());  // cloneNode
  containers.drawImage.appendChild(copyCanvas(canvas));  // cloneNode + drawImage
  containers.dataURI.appendChild(imageFromStorage(canvas));  // localStorage
}

pageLoad();
body {
  font-family: sans-serif;
}
.header {
  font-size: 18px;
}
.container {
  margin: 10px;
  display: inline-block;
}
canvas, img {
  border: 1px solid #eee;
}
#message {
  color: #666;
  font-size: 16px;
  line-height: 28px;
}
#message .time {
  display: inline-block;
  text-align: right;
  width: 100px;
}
#message .number {
  font-weight: bold;
  padding: 1px 3px;
  color: #222;
  background: #efedd4;
}
<div id="canvases"></div>

<div id="message"></div>
Copy a tile area in javascript canvas

Copy a tile area in javascript canvas


By : Ravindranath Sedidi
Date : March 29 2020, 07:55 AM
I wish this helpful for you You can use ternary operators to shorten the code, but this won't change the functionality:
Related Posts Related Posts :
  • Why onNext has no effect
  • IntelliJ Idea 2018.2 no option for importing gradle project
  • Remove a negative element from an array w/o array.copy
  • Could this prevent overflow in Java?
  • In Java Swing, can I receive Caret events in real time?
  • I need help not using brute force when using JFrames and DrawWindows
  • How do I refactor ArrayList<MyClass> into MyClassLIst?
  • My program keeps saying that the method cannot be resolved
  • BubbleSort -my code returns random addresses
  • JavaFX components inside HTML?
  • Character in Java game not responding
  • Working around access denied in a FileWalking Tree in Java7
  • How to avoid if/else when using multple suppliers?
  • How to pass object from table cell editor to Table Model?
  • Paypal Sandbox payment state pending
  • sejda-console.bat passing parameters with spaces
  • Multiple Consumers Spring Kafka
  • Bitbucket pipeline: environmental variables in build.gradle file not recognized
  • Java static enum method to return a default enum value
  • What is the complexity of empty for loop?
  • Group randomly List of Lists as N subsets with K elements in each
  • How to set texture on a shape drawn by glDrawArrays()?
  • How to make a jlabel resizable according to the window
  • Java Mathematical Expression Syntax
  • assigning values to characters in java
  • Method overriding and Inheritance in java
  • given a set of lists/groups with a series of number, find matching numbers
  • Connection to HID USB device (keyboard and mouse) in android
  • Inject HttpServletRequest in CDI SessionScoped bean
  • Pool game in java - ball collision algorithm
  • Focus ScrollView to selected position programmatically - Android
  • Is it hibernate bug?
  • Glib memory allocation error
  • Android Proguard - step by step
  • Setting the pivot point of a JPanel to its center
  • java check time is greater time
  • how to save a screenshot (matlab)
  • Anti-aliasing filled shapes in libgdx
  • Gwt custom text box having baloon popup
  • How to change date dynamically for each element in an Array
  • JPanel won't add the JLabel text?
  • how to access the .properties file in ant if it is in different location
  • Reduce application memory footprint
  • java.lang.ClassCastException: javax.mail.Session cannot be cast to javax.mail.Session
  • What is the exact purpose of calling System.exit() in java
  • How to do you get output from Javascript into Java using ScriptEngine
  • Java replaceAll() method to escape special characters
  • Java (Removing a 'keyword' from the alphabet)
  • Format BigDecimal in Spring
  • iterating checkbox values stored in array using EL
  • Java - Jackcess API with .accde(MS Access) format
  • Alternative for some of Struts 1 methods in Struts 2
  • javax.crypto JDK source code, again
  • Spring Roo - Command 'service' not found
  • antlr4: ATN version 2 expected 3
  • Deploy GlassFish using Netbeans generate java.net.MalformedURLException: Bad URL path
  • why is wait() called for loop in Thread.join() of Java?
  • Java JAXB marshall into DOM Document
  • Why JDBI 3 @ColumnName annotation doesn't work?
  • Java SimpleDateformatter with 10 decimals after the seconds, cannot convert to Date
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org